//
//  AppDelegate.m
//  minidai
//
//  Created by 谭伟 on 2017/4/19.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "AppDelegate.h"
#import "RSAUtil.h"
#import "IQKeyboardManager.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDKConnector/ShareSDKConnector.h>
#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "WXApi.h"
#import "WeiboSDK.h"
#import "ThirdPartyAPIConst.h"
#import "MNDGestureViewController.h"
#import "MNDNewFeatureView.h"
#import "MNDTabbarController.h"
#import <BaiduMobStat.h>
#import "MNDLoginUserModel.h"
#import "VTUpdateAppAlertViewController.h"

#import <UMCommon/UMCommon.h>
#import <UMPush/UMessage.h>
#import <UserNotifications/UserNotifications.h>

#import "AppDelegate+Realm.h"

@interface AppDelegate () <UNUserNotificationCenterDelegate>

@property (nonatomic, strong)MNDNewFeatureView *featureView;



@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    UITabBarController *tabBarVC = [storyBoard instantiateViewControllerWithIdentifier:@"TabbarController"];
    _window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    _window.backgroundColor = [UIColor whiteColor];
    _window.rootViewController = tabBarVC;
    [_window makeKeyAndVisible];
    
    //配置数据库
    [self configRealm];
    [self setupNetworkConfig];
    
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = @"确定";
    [IQKeyboardManager sharedManager].shouldShowToolbarPlaceholder = NO;
    
    [self cleanOldDatas];
    
    [self setupNewFeatureView];
    
    //******第三方 ******/
    [self initialShareSDK];
    
    [[BaiduMobStat defaultStat] startWithAppId:@"9f8ee6dce6"];
    
    [self configBugly];
    
    [self configUMNotifications:launchOptions];
    
    //判断是否设置了手势
    //是否开启指纹解锁
    NSString *fingerSwitchOn = [UserDefaultsTool objectForKey:kFingerPassword];
    if (fingerSwitchOn && fingerSwitchOn.length > 0) {
        [[NSNotificationCenter defaultCenter]  postNotificationName:@"showFinger" object:nil];
        
    } else {
        //取到保存的密码
        NSString *password= [UserDefaultsTool objectForKey:kGesturePassword];
        if (password && password.length > 0) {
            [[NSNotificationCenter defaultCenter]  postNotificationName:@"showGesture" object:nil];
        }
    }
    
    //兼容旧版本，将旧数据保存数据库再将UserDefaultsTool保存的数据删除
    NSDictionary *userDict = [UserDefaultsTool objectForKey:@"login_user"];
    if (userDict.count > 0) {
        MNDLoginUserModel *user = [MNDLoginUserModel mj_objectWithKeyValues:userDict];
        [MNDLoginUserModel addOrUpdateUser:user];
        [UserDefaultsTool removeForKey:@"login_user"];
    }
    
    
    
    return YES;
}


- (void)cleanOldDatas {
    
    NSString *versionKey = @"CFBundleShortVersionString";
    //取到上一次版本号
    NSString *previousVersion = [UserDefaultsTool objectForKey:versionKey];
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    NSString *preV = [previousVersion substringWithRange:NSMakeRange(0, 1)];
    //    NSString *currentV = [app_Version substringWithRange:NSMakeRange(0, 1)];
    if (preV.doubleValue < 4.0) {
        
        [UserDefaultsTool removeAllKey];
        [UserDefaultsTool saveObject:app_Version forKey:versionKey];
    }
}


- (void)setupNetworkConfig {
    [APIManager setupConfig:^(XMConfig * _Nonnull config) {
        config.generalServer = API_BASE_URL;
        config.callbackQueue = dispatch_get_main_queue();
        config.engine = [XMEngine sharedEngine];
        
        //传userCode
        MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
        if (user && user.user_code.length > 0) {
            NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", user.user_code] publicKey:RSA_PUBLIC_KEY];
            NSString *unreserved = @"";
            NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
            [allowed addCharactersInString:unreserved];
            
            NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
            config.generalHeaders = @{@"USERCODE" : encodeEncryText};
        } else {
            //            config.generalHeaders = nil;
        }
        //#ifdef DEBUG
        //        config.consoleLog = YES;
        //#endif
    }];
}

- (void)configBugly {
    BuglyConfig *buglyConfig = [[BuglyConfig alloc] init];
    buglyConfig.reportLogLevel = BuglyLogLevelError;
    buglyConfig.unexpectedTerminatingDetectionEnable = YES;
    buglyConfig.blockMonitorEnable = YES;
    
    [Bugly startWithAppId:@"965c9dfc02" config:buglyConfig];
}

/*! 友盟消息推送 */
- (void)configUMNotifications:(NSDictionary *)launchOptions {
    [UMConfigure setEncryptEnabled:YES];
    [UMConfigure initWithAppkey:@"57762f44e0f55a68d7002517" channel:@"App Store"];

    
    [UMessage setAutoAlert:NO];
    
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
    UMessageRegisterEntity *entity = [[UMessageRegisterEntity alloc] init];
    entity.types = UNAuthorizationOptionBadge | UNAuthorizationOptionAlert | UNAuthorizationOptionSound;
    
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            NSLog(@"允许通知");
        } else {
            NSLog(@"不允许通知");
        }
    }];
}

- (void)initialShareSDK {
    /**
     *  设置ShareSDK的appKey，如果尚未在ShareSDK官网注册过App，请移步到http://mob.com/login 登录后台进行应用注册，
     *  在将生成的AppKey传入到此方法中。
     *  方法中的第二个第三个参数为需要连接社交平台SDK时触发，
     *  在此事件中写入连接代码。第四个参数则为配置本地社交平台时触发，根据返回的平台类型来配置平台信息。
     *  如果您使用的时服务端托管平台信息时，第二、四项参数可以传入nil，第三项参数则根据服务端托管平台来决定要连接的社交SDK。
     */
    [ShareSDK registerActivePlatforms:@[
                                        @(SSDKPlatformTypeSinaWeibo),
                                        @(SSDKPlatformTypeWechat),
                                        @(SSDKPlatformTypeQQ)
                                        ]
                             onImport:^(SSDKPlatformType platformType)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeWechat:
                 [ShareSDKConnector connectWeChat:[WXApi class]];
                 break;
             case SSDKPlatformTypeQQ:
                 [ShareSDKConnector connectQQ:[QQApiInterface class] tencentOAuthClass:[TencentOAuth class]];
                 break;
             case SSDKPlatformTypeSinaWeibo:
                 [ShareSDKConnector connectWeibo:[WeiboSDK class]];
                 break;
                 //             case SSDKPlatformTypeSMS:
                 //                 [ShareSDKConnector connect];
                 //                 break;
             default:
                 break;
         }
     }
                      onConfiguration:^(SSDKPlatformType platformType, NSMutableDictionary *appInfo)
     {
         switch (platformType)
         {
             case SSDKPlatformTypeSinaWeibo:
                 //设置新浪微博应用信息,其中authType设置为使用SSO＋Web形式授权
                 [appInfo SSDKSetupSinaWeiboByAppKey: WeiBo_App_Key
                                           appSecret: WeiBo_App_Secret
                                         redirectUri: @"http://sns.whalecloud.com/sina2/callback"
                                            authType: SSDKAuthTypeBoth];
                 break;
             case SSDKPlatformTypeWechat:
                 [appInfo SSDKSetupWeChatByAppId: Weixin_App_ID
                                       appSecret: Weixin_App_Secret];
                 break;
             case SSDKPlatformTypeQQ:
                 [appInfo SSDKSetupQQByAppId: Tencent_App_ID
                                      appKey: Tencent_App_Secret
                                    authType: SSDKAuthTypeBoth
                                      useTIM: YES
                                 backUnionID: YES];
                 break;
             default:
                 break;
         }
     }];
}

#pragma mark -搭建新特性页面
- (void)setupNewFeatureView {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *versionkey = @"CFBundleShortVersionString";
        //取到上一次版本号
        NSString *previousVersion = [UserDefaultsTool objectForKey:@"versionkey"];
        //取到当前版本号
        NSString *currentVersion = [NSBundle mainBundle].infoDictionary[versionkey];
        
        //比较版本是否一致
        if ([currentVersion isEqualToString:previousVersion]) {
            [self.featureView removeFromSuperview];
            
        } else {
            
            self.featureView = [[MNDNewFeatureView alloc]initWithFrame:self.window.bounds];
            self.featureView.backgroundColor = [UIColor yellowColor];
            self.featureView.featurePictureArray = @[@"feature_one",@"feature_two",@"feature_three"];
            [self.window addSubview:self.featureView];
            
            //保存版本号
            [UserDefaultsTool saveObject:currentVersion forKey:@"versionkey"];
        }
    });
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    //记录程序进入后台的时间,并保存
    NSDate *date = [NSDate date];
    [UserDefaultsTool saveObject:date forKey:@"enterBackgroundTime"];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    NSDate *enterBackgroundTime = [UserDefaultsTool objectForKey:@"enterBackgroundTime"];
    //计算间隔
    NSInteger interval = [enterBackgroundTime timeIntervalSinceNow];
    //取到保存的密码
    NSString *password= [UserDefaultsTool objectForKey:kGesturePassword];
    //如果已设置手势密码,已登陆,并且进入后台时间超过10秒，弹出手势解锁
    if(interval < -10 ) {
        
        //是否开启指纹解锁
        NSString *fingerSwitchOn = [UserDefaultsTool objectForKey:kFingerPassword];
        if ([fingerSwitchOn  isEqualToString:@"YES"]) {
            [[NSNotificationCenter defaultCenter]  postNotificationName:@"showFinger" object:nil];
            
        }else if(password.length > 0 && fingerSwitchOn == NO){
            [[NSNotificationCenter defaultCenter]  postNotificationName:@"showGesture" object:nil];
        }else {
            
        }
    }
    
//    [self loadAppVersionInfo];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

#pragma mark - mark - 消息推送

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSLog(@"Device Token: %@", [self stringDevicetoken:deviceToken]);
}

//iOS10以下使用
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    //关闭友盟自带的弹出框
    [UMessage setAutoAlert:NO];
    [UMessage sendClickReportForRemoteNotification:userInfo];
    [UMessage didReceiveRemoteNotification:userInfo];
    
    NSLog(@"收到消息: %@", userInfo);
}

//iOS 10以上使用
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [UMessage setAutoAlert:NO];
    [UMessage sendClickReportForRemoteNotification:userInfo];
    
    if([[[UIDevice currentDevice] systemVersion]intValue] < 10){
        [UMessage didReceiveRemoteNotification:userInfo];
        completionHandler(UIBackgroundFetchResultNewData);
    }
}

//iOS10新增：处理前台收到通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler{
    NSDictionary *userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于前台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        
    }else{
        //应用处于前台时的本地推送接受
    }
    NSLog(@"收到通知了： %@", userInfo);
}

//iOS10新增：处理后台点击通知的代理方法
-(void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler{
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //应用处于后台时的远程推送接受
        //必须加这句代码
        [UMessage didReceiveRemoteNotification:userInfo];
        [[NSNotificationCenter defaultCenter] postNotificationName:kPushMsgIINotification object:userInfo];
    }else{
        //应用处于后台时的本地推送接受
    }
    NSLog(@"收到通知了： %@", userInfo);
}

#pragma mark 以下的方法仅作调试使用
-(NSString *)stringDevicetoken:(NSData *)deviceToken
{
    NSString *token = [deviceToken description];
    NSString *pushToken = [[[token stringByReplacingOccurrencesOfString:@"<"withString:@""]
                            stringByReplacingOccurrencesOfString:@">"withString:@""] stringByReplacingOccurrencesOfString:@" "withString:@""];
    return pushToken;
}

#pragma mark -弹出手势锁判定
//
//- (void)showGestureLock:(UIApplication *) {
//
//    //获取进入后台时间
//
//
//
//
////        [[NSNotificationCenter defaultCenter]  postNotificationName:@"showGesture" object:nil];
////        [UserDefaultsTool saveBool:YES forKey:@"confirmPassword"];
//    }
//}


@end
